<template>
  <div class="app-container">
    <div class="container-box">
      <div class="table-title text-primary"> 广播组</div>
      <div class="filter-container">
        <el-input v-model="listQuery.title" placeholder="查询内容" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.type" placeholder="查询类型" clearable class="filter-item" style="width: 130px;margin-left: 10px;">
          <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select v-model="listQuery.status" placeholder="活动状态" clearable class="filter-item" style="width: 130px;margin-left: 10px;" @change="getList">
          <el-option v-for="item in calendarStatusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          添加广播组
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="#编号" prop="id" sortable="custom" align="center" width="70" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="活动名称" width="110px" align="center">
          <template slot-scope="{row}">
            <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.activityName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起人" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.hostname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起社团" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.hostOrg }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参与人" min-width="110px" align="left">
          <template slot-scope="{row}">
            <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.participant }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Status" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="toDetail(row.id)">
              详情
            </el-button>
            <el-button size="mini" type="info" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
            <el-button circle icon="el-icon-chat-dot-round" style="background-color: #409EFF;color: white" @click="toChat(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="temp.activityName" />
        </el-form-item>
        <el-form-item label="发起人" prop="name">
          <el-input v-model="temp.hostname" />
        </el-form-item>
        <el-form-item label="发起人学号" prop="userId">
          <el-input v-model="temp.userId" />
        </el-form-item>
        <el-form-item label="社团">
          <el-select v-model="temp.hostOrg" class="filter-item" placeholder="Please select">
            <el-option v-for="item in orgOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="举办场所">
          <el-input v-model="temp.needPlace" />
        </el-form-item>
        <el-form-item label="参加社团">
          <el-drag-select v-model="participantOrg" style="width: 300px" multiple placeholder="请选择">
            <el-option v-for="item in orgOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-drag-select>
        </el-form-item>
        <el-form-item label="预计规模">
          <el-input v-model="temp.scale" />
        </el-form-item>
        <div class="text-danger">*参与者在详情处设置</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ElDragSelect from '@/components/DragSelect'
import { fetchPv, createArticle, updateArticle } from '@/api/article'
import { fetchActivityList } from '@/api/activity'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'name', display_name: '发起人姓名' },
  { key: 'class', display_name: '班级' },
  { key: 'org', display_name: '社团' }
]
const calendarStatusOptions = [
  { key: '0', display_name: '禁用' },
  { key: '1', display_name: '活跃' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Activity',
  components: { Pagination, ElDragSelect },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '活跃': 'success',
        '禁用': 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      chart: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        type: '',
        title: '',
        page: 1,
        limit: 10,
        onlyWorking: true
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      calendarStatusOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      genderOptions: ['男', '女'],
      statusOptions: ['在职', '离队', '退役'],
      positionOptions: ['社长', '部长', '干事'],
      orgOptions: [{
        value: '计算机服务队',
        label: '计算机服务队'
      }, {
        value: '软件俱乐部',
        label: '软件俱乐部'
      }, {
        value: '自行车协会',
        label: '自行车协会'
      }, {
        value: '红会',
        label: '红会'
      }, {
        value: '学生会',
        label: '学生会'
      }],
      showReviewer: false,
      temp: {
        activityName: '',
        userId: '',
        hostname: '',
        hostOrg: '',
        participantOrg: '',
        participant: '',
        scale: '',
        status: '申请中',
        needPlace: '',
        open: ''
      },
      dialogFormVisible: false,
      deleteDialogFormVisible: false,
      deleteTemp: -1,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      participantOrg: ['Apple', 'Banana', 'Orange']
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchActivityList(this.listQuery).then(res => {
        this.list = res.data.items
        this.total = res.data.total
        for (var i in this.list) {
          this.list[i]['participant'] = ''
          this.list[i]['participantOrg'] = ''
          for (var j in this.list[i].participantList) { this.list[i].participant += this.list[i].participantList[j] + ', ' }
          for (j in this.list[i].participantOrgList) { this.list[i].participantOrg += this.list[i].participantOrgList[j] + ', ' }
          this.list[i].participant = this.list[i].participant.substring(0, this.list[i].participant.lastIndexOf(','))
          this.list[i].participantOrg = this.list[i].participantOrg.substring(0, this.list[i].participantOrg.lastIndexOf(','))
        }
        console.log(this.list)
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    toDetail(id) {
      this.$router.push({ path: '/broadcast/detail/' + id })
    },
    toChat(row) {
      this.$router.push({ path: '/inform/p2g/' + row.id })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        intro: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'organization-manage-system-webapp'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      this.deleteDialogFormVisible = true
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    deleteData() {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(this.deleteTemp, 1)
      this.deleteTemp = -1
      this.deleteDialogFormVisible = false
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '性别', '社团', '职位', '状态', '简介']
        const filterVal = ['id', 'name', 'gender', 'org', 'position', 'status', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '社团成员表（总）'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style lang="scss" scoped>
  .container-box{
    margin: 20px;
    padding: 30px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
  .table-title{
    font-weight: bolder;
    font-size: 25px;
    margin-bottom: 20px;
  }
  .form-item{
    display: flex;
    flex-direction: row;
    font-size: 20px;
    margin: 5px;
  }
  .form-label{
    font-weight: bold;
  }
  .form-value{
    color: #7d7d7f;
  }
</style>
